package com.lagou;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import org.I0Itec.zkclient.ZkClient;

import java.sql.*;

public class TestDruid {

    private static DruidDataSource dataSource;


    public static void close(){
        dataSource.close();
    }

    public static void initDataSource(ZkClient zkClient) throws SQLException {
        String s = zkClient.readData("/zkServerDruid-Ep");
        System.out.println(s);
        DataSourceConfig dataSourceConfig = JSON.parseObject(s, DataSourceConfig.class);

        dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dataSourceConfig.getDriverClassName());//"com.mysql.jdbc.Driver"
        dataSource.setUsername(dataSourceConfig.getUsername());//"root"
        dataSource.setPassword(dataSourceConfig.getPassword());//"root"
        dataSource.setUrl(dataSourceConfig.getUrl());//"jdbc:mysql://127.0.0.1:3306/zdy_mybatis"
        dataSource.setInitialSize(dataSourceConfig.getInitialSize());//5
        dataSource.setMinIdle(dataSourceConfig.getMinIdle());//1
        dataSource.setMaxActive(dataSourceConfig.getMaxActive()); // 10 启用监控统计功能
        dataSource.setFilters("stat");// for mysql  dataSource.setPoolPreparedStatements(false);

    }

    public static void doSql() throws SQLException {
        Connection connection = dataSource.getConnection();//获取连接

        //查询出部门编号、部门名称、部门位置、每个部门的员工人数
        String sql =" SELECT * FROM t_article ;";

        //获取语句执行者等一系列操作
        PreparedStatement ps = connection.prepareStatement(sql);

        ResultSet resultSet = ps.executeQuery();

        while (resultSet.next()) {
//            System.out.println(resultSet.getRow());
            int id = resultSet.getInt("id");
            String title = resultSet.getString("title");
            String content = resultSet.getString("content");
            System.out.println("id="+id+" title="+title+" content="+content );

        }
        System.out.println("===================================================================");
    }

    public static void main(String[] args) throws SQLException {

        initDataSource(InitZkNode.getZkClient());
        doSql();


        //释放资源
//        dataSource.close();


//        .closeResource(resultSet,ps,connection);
//        Utils11.closeResource(resultSet1,ps1,null);
//        Utils11.closeResource(resultSet2,ps2,null);




//        dataSource.restart();



    }

}
